/**
 * 
 */
package idv.takeshi.software.productline.bookstore.presentation.web.tag;

import idv.takeshi.software.productline.bookstore.utils.text.StripTagUtils;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Show book description to jsp page.
 * @author takeshi
 *
 */
public class BookDescriptionTagHandler extends SimpleTagSupport {
	
	private static final Log log = LogFactory.getLog(BookDescriptionTagHandler.class);
	
	private int length = 250;
	
	private String text;

	/* (non-Javadoc)
	 * @see javax.servlet.jsp.tagext.SimpleTagSupport#doTag()
	 */
	@Override
	public void doTag() throws JspException, IOException {
		final String msg = "generate book description content failed";
		try{
			JspWriter writer = this.getJspContext().getOut();
			super.doTag();
			String text = null;
			int toIndex = 0;
			
			if(StringUtils.isNotBlank(this.text)){
				text = StripTagUtils.stripTags(this.text);
			} else{
				text = "";
			}
			
			toIndex = text.length() < this.length? (text.length() - 1): (this.length - 1);
			toIndex = toIndex == -1? 0: toIndex;
			
			text = text.substring(0, toIndex);
			writer.print(text + "...");
			
		} catch(JspException e){
			log.error(msg, e);
			throw e;
		} catch(IOException e){
			log.error(msg, e);
			throw e;
		}
	}

	/**
	 * @return the length
	 */
	public int getLength() {
		return length;
	}

	/**
	 * @param length the length to set
	 */
	public void setLength(int length) {
		this.length = length;
	}

	/**
	 * @return the text
	 */
	public String getText() {
		return text;
	}

	/**
	 * @param text the text to set
	 */
	public void setText(String text) {
		this.text = text;
	}

}
